package com.wing.system.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.config.BaseDataInit;
import com.wing.platform.feign.PlatformClient;
import com.wing.system.dao.ClientCaseDao;
import com.wing.system.model.entity.ClientCase;
import com.wing.system.model.request.ClientCaseForm;
import com.wing.system.model.response.ClientCaseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 客户案例-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ClientCaseServiceImpl extends ServiceImpl<ClientCaseDao, ClientCase> implements ClientCaseService {
    @Autowired
    private PlatformClient platformClient;
    @Autowired
    private BaseDataInit baseDataInit;
    @Override
    @Transactional
    public int add(ClientCaseForm clientCaseForm) {

        //校验

        ClientCase clientCase =new ClientCase();
        CopyOptions copyOptions = CopyOptions.create()

        .setEditable(ClientCase.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(clientCaseForm, clientCase, copyOptions);
        int insert = baseMapper.insert(clientCase);
        // 同步到平台
        if(insert>0){
            com.wing.platform.order.model.entity.ClientCase platformClientCase= new com.wing.platform.order.model.entity.ClientCase();
            //利用json 实现类的相互转换
            platformClientCase = JSON.parseObject(JSON.toJSONString(clientCase), com.wing.platform.order.model.entity.ClientCase.class);
            platformClientCase.setEnterpriseId(baseDataInit.ENTERPRISE_DATA.getId());
            platformClientCase.setSubstituteId(clientCase.getId());
            JsonResult jsonResult = platformClient.clientCaseAdd(platformClientCase);
            if(jsonResult.getCode()!=200){
                return 0;
            }


        }
        return insert;
    }

    @Override
    public List<ClientCaseVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ClientCaseVO> pageList4app(Page page, Map<String, Object> params) {
        List<ClientCaseVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ClientCaseVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }
}
